﻿//utility begin
/*  var strActual = String.format("yes, {0}, {1}", "lmj", "haha");
var strExpect = "yes, lmj, haha";
*/
String.format = function () {
    if (arguments.length == 0) {
        return null;
    }
    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {

        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}
//utility end

/*  example for test qunit, useless
*/
function AddTemp(a, b) {
    return a + b;
}

/*  Init papaer structor to accordion
*/
function InitPaperData() {
    $("#ComplexQuestion").css("display", "none");
    $("#SingleQuestion").css("display", "none");
    var $accordion = $("#accordion");
    var i = 0;
    var j = 0;
    for (var i = 0; i < $paper.PaperTemplate.PaperTemplateParts.length; i++) {
        var str = String.format("<h3><a href='#'>{0}</a></h3><div>", $paper.PaperTemplate.PaperTemplateParts[i].PaperTemplatePartName);
        for (j = 0; j < $paper.PaperDetails.length; j++) {
            if ($paper.PaperTemplate.PaperTemplateParts[i].PaperTemplatePartCode != $paper.PaperDetails[j].PaperTemplatePartCode) {
                continue;
            }
            str = str + String.format("<div class='questionno'><span class='questionNoSpan'>{0}</span><span>第 {1} 题</span></div>", $paper.PaperDetails[j].QuestionNo, $paper.PaperDetails[j].QuestionNo);
        }
        str = str + "</div>";
        $accordion.append(str);
    }

    $("#first").click(GotoQuestionFirst);
    $("#pre").click(GotoQuestionPre);
    $("#next").click(GotoQuestionNext);
    $("#last").click(GotoQuestionLast);
    $("#submitpaper").click(SubmitPaper);
    $("#markcurrentquestion").click(MarkCurrentQuestion);
    $("#examattention").click(ExamAttention);

    $("#now").text("第1题");
    $("#all").text(String.format("共{0}题", $paper.PaperDetails.length));
}

/*  set the action: when click the div questionno , then the content should be showed.
*/
function SetQuestionnoDivClick() {
    var $questionno = $(".questionno");
    var $questionStemCode = $(".QuestionStemCode");
    var $questionStemContent = $(".QuestionStemContent");
    $questionno.click(function () {
        var currentQuestionNo = $(".questionNoSpan", this).text();
        $("#now").text(String.format("第{0}题", currentQuestionNo));
        $.each($paper.PaperDetails, function (i, item) {
            if (currentQuestionNo == item.QuestionNo) {
                $("#SingleQuestion .QuestionStemCode").html($paper.PaperDetails[i].QuestionStemCode);
                ShowDifferentByDifferentQuestion(i);
            }
        });
    });
}

/*  Set the choice option clicked interaction  
//  find the question, and the current option
//  if the current option's IsStudentSelected == true ,then 
//      set false
//  else
//      set true
//  end if
//  find the left options, then
//      set false
//  find all parent's children
//      init background-color == selected
//  if current IsStudentSelected == true ,then 
//      set background-color=SelectedColor;
//  else
//      set unSelectedColor
//end note
*/
function SetOptionLiClick() {
    var currentOptionCode = $(".OptionCode", this).text();
    var currentStemCode = $(this).parent().parent().children(".QuestionStemCode").text();
    var currentDetail;
    $.each($paper.PaperDetails, function (i, itemDetail) {
        if (itemDetail.QuestionStemCode == currentStemCode) {
            currentDetail = itemDetail;
        }
    });
    $("#now").text(String.format("第{0}题", currentDetail.QuestionNo));
    var currentOption;
    $.each(currentDetail.QuestionOptions, function (i, itemOption) {
        if (itemOption.QuestionOptionCode == currentOptionCode) {
            currentOption = itemOption;
        }
    });

    if (currentOption.IsStudentSelected == true) {
        currentOption.IsStudentSelected = false;
        MarkUnAnswered();
    }
    else {
        currentOption.IsStudentSelected = true;
        MarkAnswered();
    }
    $.each(currentDetail.QuestionOptions, function (i, itemOption) {
        if (itemOption.QuestionOptionCode != currentOptionCode) {
            itemOption.IsStudentSelected = false;
        }
    });
    $(this).parent().children().css("background-color", optionUnSelectedColor);
    if (currentOption.IsStudentSelected == true) {
        $(this).css("background-color", optionSelectedColor);
    }
    SaveOptionDetail(currentDetail);
}

/*  Init contentright, and show the questions, and init the interactivity of the question
*/
function ShowDifferentByDifferentQuestion(paperNumIndex) {
    var $detail = $paper.PaperDetails[paperNumIndex];

    if ($detail.IsComplex == 0) {
        $("#ComplexQuestion").css("display", "none");
        $("#SingleQuestion").css("display", "block");
        //just show one question
        $("#SingleQuestion .QuestionUnitBaseName").html($detail.QuestionUnitBaseName);
        $("#SingleQuestion .QuestionStemCode").html($detail.QuestionStemCode);
        $("#SingleQuestion .QuestionStemContent").html(String.format("第{0}题：{1}", $detail.QuestionNo, unescape($detail.QuestionStemContent)));
        $("#SingleQuestion .OptionUl li").remove();
        $("#SingleQuestion .OptionUl").append(InitOptionLi($detail));
        SubjectiveAnswerInitAndShow($detail);
    }

    if ($detail.IsComplex == 1) {
        $("#SingleQuestion").css("display", "none");
        $("#ComplexQuestion").css("display", "block");
        //show the complex question ,include show all children questions
        var childQuestions = GetChildrenQuestionByFaceCode($detail.QuestionFaceCode);
        $("#ChildrenQuestions li").remove();
        $.each(childQuestions, function (i, itemQuestion) {
            var innerHtml = String.format("<li><div class='QuestionUnitBaseName'>{0}</div>"
                                    + "<div class='QuestionStemCode'>{1}</div>"
                                    + "<div class='QuestionStemContent'>第{2}题：{3}</div>"
                                    + "<ul class='OptionUl'>",
                                    itemQuestion.QuestionUnitBaseName,
                                    itemQuestion.QuestionStemCode,
                                    itemQuestion.QuestionNo,
                                    unescape(itemQuestion.QuestionStemContent));
            innerHtml += InitOptionLi(itemQuestion);
            innerHtml = innerHtml + "</ul></li>";
            $(".QuestionFaceCode").html(itemQuestion.QuestionFaceCode);
            $(".QuestionFaceContent").html(unescape(itemQuestion.QuestionFaceContent));
            $("#ChildrenQuestions").append(innerHtml);
            //scroll to current clicked questionno
            if (itemQuestion.QuestionNo == (paperNumIndex + 1)) {
                var rowpos = $("#ChildrenQuestions li:last").position();
                $(".contentright").scrollTop(rowpos.top);
            }
        });

    }

    $(".OptionUl li").click(SetOptionLiClick);
}

/*  get all children questions by questionFaceCode
*/
function GetChildrenQuestionByFaceCode(questionFaceCode) {
    var childQuestions = new Array();
    //get all children questions
    $.each($paper.PaperDetails, function (i, item) {
        if (item.QuestionFaceCode == questionFaceCode) {
            childQuestions.push(item);
        }
    });
    return childQuestions;
}

/*
*/
function GotoQuestionFirst() {
    $(".questionno:first").click();
}

/*
*/
function GotoQuestionPre() {
    //if current is first , return
    var questionNo = GetQuestionNoByNowDiv();
    if (questionNo - 1 < 2) {
        return;
    }
    var index = questionNo - 1 - 1;
    $(".questionno:eq(" + index + ")").click();
}

/*
*/
function GotoQuestionNext() {
    //if current is last, return
    var questionNo = GetQuestionNoByNowDiv();
    if (questionNo > $paper.PaperDetails.length) {
        return;
    }
    var index = questionNo;
    $(".questionno:eq(" + index + ")").click();
}

/*
*/
function GotoQuestionLast() {
    //$(".questionno:last").click();
    $(".questionno:last").click();
}


/*
*/
function SubmitPaper() {
    alert("SubmitPaper");
}

/*
*/
function MarkCurrentQuestion() {
    alert("MarkCurrentQuestion");
}

/*
*/
function ExamAttention() {
    alert("ExamAttention");
    $(".questionno:eq(" + 1 + ")").css("background-color", "red");
}

/*
*/
function GetQuestionNoByNowDiv() {
    var questionNoText = $("#now").text();
    return questionNoText.substring(1, questionNoText.length - 1);
}

function MarkAnswered() {
    var questionNo = GetQuestionNoByNowDiv();
    $(".questionno:eq(" + (questionNo - 1) + ")").css("background-color", questionAnsweredColor);
}

function MarkUnAnswered() {
    var questionNo = GetQuestionNoByNowDiv();
    $(".questionno:eq(" + (questionNo - 1) + ")").css("background-color", questionUnAnsweredColor);
}


/*  deal with the SubjectiveAnswer textarea
*/
function SubjectiveAnswerInitAndShow($detail) {
    /*  deal with the size
    //  set the QuestionAnswer to SubjectiveAnswer textarea
    //  init a timer to save the answer
    //  set the interactity that if blur, then save answer
    */
    if ($("#SingleQuestion .QuestionUnitBaseName").text() == "论述题") {
        $("#SingleQuestion .SubjectiveAnswer").css("display", "block");
        $("#SingleQuestion .SubjectiveAnswer").css("width", "100%");
        if ($detail.QuestionUnitName == "汉译英") {
            $("#SingleQuestion .SubjectiveAnswer").css("height", "50px");
        }
        if ($detail.QuestionUnitName == "写作") {
            $("#SingleQuestion .SubjectiveAnswer").css("height", "300px");
        }
    }
    else {
        $("#SingleQuestion .SubjectiveAnswer").css("display", "none");
    }

    InitDetailTextArea($detail);
    $(".SubjectiveAnswer").unbind("keyup");
    $(".SubjectiveAnswer").keyup(function () {
        SaveSubjectiveDetail($detail);
    });
}

/*  init the detail answer
*/
function InitDetailTextArea($detail) {
    if ($detail.QuestionAnswer == null) {
        $detail.QuestionAnswer = "";
    }
    $("#SingleQuestion .SubjectiveAnswer").text($detail.QuestionAnswer);
}

/*  init the option answer
*/
function InitOptionLi(detail) {
    var liInnerHtml = "";
    $.each(detail.QuestionOptions, function (i, itemOption) {
        if (itemOption.IsStudentSelected == true) {
            liInnerHtml = liInnerHtml + String.format("<li style='background-color:#BBF195'><span class='OptionCode'>{0}</span><span>{1}</span></li>", itemOption.QuestionOptionCode, unescape(itemOption.OptionsValue));
        }
        else {
            liInnerHtml = liInnerHtml + String.format("<li><span class='OptionCode'>{0}</span><span>{1}</span></li>", itemOption.QuestionOptionCode, unescape(itemOption.OptionsValue));
        }
    });
    return liInnerHtml;
}

/*  if is in subject, then save subjective answer
//if current length - old length > 5
//  save, and set the shouldBeSave = true
*/
function SaveSubjectiveDetail(currentDetail) {
    currentDetail.QuestionAnswer = $("#SingleQuestion .SubjectiveAnswer").text();
    document.title = new Date();
    shouldBeSave = true;
    MarkAnswered();
}

/*  save SaveOptionDetail, and set the shouldBeSave = true
*/
function SaveOptionDetail(currentdetail) {
    currentdetail.QuestionChoicesAnswer = "";
    $.each(currentdetail.QuestionOptions, function (i, itemOption) {
        if (itemOption.IsStudentSelected) {
            currentdetail.QuestionChoicesAnswer += itemOption.OptionsKey + "|";
        }
    });
    if (currentdetail.QuestionChoicesAnswer.indexOf("|") > 0) {
        currentdetail.QuestionChoicesAnswer.substring(0, currentdetail.QuestionChoicesAnswer.length - 1);
    }
    shouldBeSave = true;
}

/*  SavePaper to server
*/
function SavePaper() {
    window.setInterval(function () {
        //alert("dd");
        if (shouldBeSave == true) {
            $paper.CreateTime = null;
            var options = {
                type: "POST",
                contentType: "application/json",
                url: "../../paper.html/SavePaper",
                data: JSON.stringify($paper),
                success: function (response) {
                    //alert(response);
                },
                error: function (xmlhttpequest, msg, catchobj) {
                    alert(msg);
                },
                dataType: "json"
            };
            var returnText = $.ajax(options).responseText;
            shouldBeSave = false;
        }
    }, saveIntervalMillSeconds);
}